﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CoreHelper.Validation.Validators;

namespace CoreHelper.Validation
{
    public static class Validator
    {

        internal static Dictionary<string, Func<object, ValidationContext, bool>> m_customValidators = new Dictionary<string, Func<object, ValidationContext, bool>>();

        public static void RegisterCustomValidator(string key, Func<object, ValidationContext, bool> fun)
        {
            m_customValidators[key] = fun;
        }

        public static ValidResultObject ValidateObject(object instance)
        {
            if (instance == null) return new ValidResultObject { Msg = "instance 不能为空" };
            var validationContext = new ValidationContext(instance);
            return Validate(validationContext);
        }

        public static ValidResultObject ValidateParams(List<ValidationItem> ps)
        {
            var validationContext = new ValidationContext(ps);
            return Validate(validationContext);
        }

        private static ValidResultObject Validate(ValidationContext validationContext)
        {
            ValidResultObject result = new ValidResultObject();
            result.Success = true;
            result.Result = new List<ValidResultObject.ValidResultItem>();

            foreach (var item in validationContext.ValidationList)
            {
                if (item.Validations.Count > 0)
                {
                    //如果不是必须的
                    if (item.Validations.First().GetType().Name != nameof(RequiredValidatorAttribute))
                    {
                        if (item.Value == null || item.Value.ToString().Length == 0)
                        {
                            continue;
                        }
                    }
                    var errorMessages = new List<string>();
                    foreach (var validation in item.Validations)
                    {
                        if (!validation.IsValid(item.Value, validationContext))
                        {
                            errorMessages.Add(validation.FormatErrorMessage());
                        }
                    }
                    if (errorMessages.Count > 0)
                    {
                        var resultItem = new ValidResultObject.ValidResultItem()
                        {
                            Name = item.Name,
                            Value = item.Value,
                            ErrorMessages = errorMessages
                        };
                        result.Result.Add(resultItem);
                    }
                }
            }
            if (result.Result.Count > 0)
            {
                result.Code = 0;
                result.Success = false;
                result.Msg = result.Result.First().ErrorMessages.First();
            }
            return result;
        }
    }
}
